package com.iot.common.mybatis;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/*
   <columnOverride column="json_string" javaType="com.alibaba.fastjson.JSONObject" typeHandler="JSONObjectTypeHandler"/>
 */
public class JSONObjectTypeHandler extends BaseTypeHandler<JSONObject> {
    private static final ObjectMapper mapper = new ObjectMapper();


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JSONObject parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.toJSONString());
    }

    @Override
    public JSONObject getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String jsonSource = rs.getString(columnName);
        if (jsonSource == null) {
            return null;
        }
        try {
            JSONObject jsonNode = JSONObject.parseObject(jsonSource);
            return jsonNode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public JSONObject getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String jsonSource = rs.getString(columnIndex);
        if (jsonSource == null) {
            return null;
        }
        try {
            JSONObject jsonNode = JSONObject.parseObject(jsonSource);
            return jsonNode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    public JSONObject getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String jsonSource = cs.getString(columnIndex);
        if (jsonSource == null) {
            return null;
        }
        try {
            JSONObject jsonNode = JSONObject.parseObject(jsonSource);
            return jsonNode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}